<template>
	<input type="file" ref="inputRef" @change="uploadChange" />
	<div @click="uploadClick">
		<slot></slot>
	</div>
</template>
<script setup>
import { ref } from "vue";
import { UploadTools, Upload } from "@/api/request";
import { ElMessage } from "element-plus";
const inputRef = ref();
const props = defineProps({
	data: Object,
	/**
	 * @Description: 上传前钩子，返回true或者promise.reslove(true)即可执行上传
	 * @MethodAuthor: 于波
	 * @Date: 2022-10-18 22:22:10
	 */
	beforeUpload: Function,
	/**
	 * @Description: 文件选择前钩子，返回true或者promise.reslove(true)即可执行上传
	 * @MethodAuthor: 于波
	 * @Date: 2022-10-18 22:22:10
	 */
	beroreChooseFile: Function,
});
const emit = defineEmits(["onUploadProgress", "onComplate"]);
const uploadClick = async () => {
	if (props.beroreChooseFile) {
		let res = await props.beroreChooseFile();
		if (res) {
			inputRef.value.click();
		}
	} else {
		inputRef.value.click();
	}
};
const onUploadProgress = (e) => {
	emit("onUploadProgress", e);
};
const uploadChange = async (event) => {
	let fileList = event.target.files;
	// 清空
	event.target.type = "text";
	event.target.value = "";
	event.target.type = "file";
	const formData = new FormData();
	// 拼接参数
	if (props.data) {
		Object.keys(props.data).forEach((item) => {
			formData.append(item, props.data[item]);
		});
	}
	formData.append("file", fileList[0]);
	if (props.beforeUpload != undefined) {
		let result = await props.beforeUpload(fileList[0]);
		if (result) {
			let res = await Upload(formData, onUploadProgress);
			emit("onComplate", res.data);
		}
	} else {
		let res = await Upload(formData, onUploadProgress);
		emit("onComplate", res.data);
	}
};
</script>
<style scoped>
input {
	display: none;
}
</style>
